<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query['product.nameCn']"
          clearable
          placeholder="产品名"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="modelCreatedAt" class="date-item" :fix-date.sync="query.firstEnterDate" />
        <!-- 搜索 -->
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission">
        <template slot="right">
          <!--          <el-button-->
          <!--            class="filter-item"-->
          <!--            size="mini"-->
          <!--            type="primary"-->
          <!--            icon="el-icon-plus"-->
          <!--            @click="open"-->
          <!--          >-->
          <!--            初始化-->
          <!--          </el-button>-->
        </template>
      </crudOperation>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        stripe
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column label="产品名" width="300">
          <template slot-scope="scope">
            <div class="productInfo">
              <img :src="baseApi + scope.row.product.pic" class="tableImg" alt="">
              <span>{{ scope.row.product.nameCn }}</span>
              <div />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="產品編號" sortable>
          <template slot-scope="scope">
            {{ scope.row.product.sku }}
          </template>
        </el-table-column>
        <el-table-column prop="depot.name" label="仓库" sortable />
        <el-table-column prop="quantity" label="总库存" sortable />
        <el-table-column prop="applyQuantity" label="可用库存" sortable />
        <el-table-column prop="occupyQuantity" label="占用库存" sortable />
        <el-table-column prop="firstEnterDate" label="入库时间" sortable />
        <el-table-column prop="lastLeaveDate" label="出库时间" sortable />
        <el-table-column prop="lastVendor" label="入庫供應商" sortable />
        <el-table-column
          label="操作"
          align="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="stockLog(scope.row)"
            >
              日志
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false">
        <el-button type="primary" @click="choose">
          添加商品
        </el-button>
        <el-table
          :data="tableData"
          style="width: 100%"
          size="small"
          height="600px"
          stripe
        >
          <el-table-column
            label="产品名"

            width="200px"
          >
            <template slot-scope="scope">
              <div class="productInfo">
                <img :src="baseApi + pic[scope.$index]" class="tableImg" alt="">
                <span>{{ nameCn[scope.$index] }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sku"

            width="200px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.sku }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" size="mini" :min="0" />
            </template>
          </el-table-column>
          <el-table-column
            prop="depotId"
            label="仓库"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.depotId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loading"
              >
                <el-option
                  v-for="item in vendorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native.prevent="deleteRow(scope.$index, tableData)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 20px">
          <el-button class="button4" size="mini" @click="dialogVisible=false">取消</el-button>
          <el-button class="button3" size="mini" type="primary" @click="initializeWarehouse">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="visible" :close-on-click-modal="false" width="80%">
        <el-table
          :data="logData"
          style="width: 100%"
          size="small"
          height="600px"
          stripe
        >
          <el-table-column
            label="业务编号"
            prop="businessNumber"
          />
          <el-table-column
            label="业务类型"
            prop="stockLogBusinessType"
          >
            <template slot-scope="scope">
              <el-tag effect="plain" type="success">{{
                dict.label.stockLogBusinessType[scope.row.stockLogBusinessType]
              }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="仓库"
            prop="depot.name"
          />
          <el-table-column
            label="产品名"
            prop="product.nameCn"

            width="400px"
          />
          <el-table-column
            label="產品編號"
            prop="product.sku"
          />
          <el-table-column
            label="总库存	"
            prop="changeAfterTotal"
          >
            <template slot-scope="scope">
              {{ scope.row.changeBeforeTotal }} <i class="el-icon-right" /> {{ scope.row.changeAfterTotal }}
              <span v-if="scope.row.changeAfterTotal - scope.row.changeBeforeTotal !== 0 ">
                <i
                  v-if="scope.row.changeAfterTotal - scope.row.changeBeforeTotal >0 "
                  class="el-icon-top"
                  style="color: green"
                />
                <i v-else class="el-icon-bottom" style="color: red" /> {{ scope.row.changeCountTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="可用库存"
          >
            <template slot-scope="scope">
              {{ scope.row.changeBeforeApply }} <i class="el-icon-right" /> {{ scope.row.changeAfterApply }}
              <i
                v-if="scope.row.changeAfterApply - scope.row.changeBeforeApply > 0 "
                class="el-icon-top"
                style="color: green"
              />
              <i v-else class="el-icon-bottom" style="color: red" /> {{ scope.row.changeCountApply }}
            </template>
          </el-table-column>
          <el-table-column
            label="占用库存"
          >
            <template slot-scope="scope">
              {{ scope.row.changeBeforeOccupy }} <i class="el-icon-right" /> {{ scope.row.changeAfterOccupy }}
              <i
                v-if="scope.row.changeAfterOccupy - scope.row.changeBeforeOccupy > 0 "
                class="el-icon-top"
                style="color: green"
              />
              <i v-else class="el-icon-bottom" style="color: red" /> {{ scope.row.changeCountOccupy }}
            </template>
          </el-table-column>
          <el-table-column
            label="備註"

            prop="operateNote"
            width="200px"
            show-tooltip-when-overflow
          />

          <el-table-column
            label="操作类型"
            prop="type"
            column-key="type"

            :filters="[{text: '增加', value: '1'}, {text: '减少', value: '0'}, {text: '不变', value: '2'}]"
            :filter-method="filterTypeHandler"
          >
            <template slot-scope="scope">
              <el-tag type="success">{{ dict.label.logOperationType[scope.row.type] }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <choose-product ref="chooseProduct" @childNotify="childNotify" />
  </div>
</template>

<script>
import crudStock from '@/api/wms/stock'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import chooseProduct from '@/components/product'
import depotApi from '@/api/wms/depot'
import DateRangePicker from '@/components/DateRangePicker'
import rrOperation from '@crud/RR.operation'

const defaultForm = {
  id: null,
  depotId: null,
  productId: null,
  quantity: null,
  applyQuantity: null,
  occupyQuantity: null,
  frozenQuantity: null,
  firstEnterDate: null,
  lastLeaveDate: null
}
export default {
  name: 'Stock',
  components: { pagination, crudOperation, rrOperation, chooseProduct, DateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      visible: false,
      modelCreatedAt: '', // 时间选择器显示时间
      nameCn: [],
      pic: [],
      tableData: [],
      logData: [],
      list: [],
      loading: false,
      vendorOptions: [],
      arrId: [],
      dialogVisible: false,
      permission: {
        add: ['admin', 'stock:add'],
        edit: ['admin', 'stock:edit'],
        del: ['admin', 'stock:del']
      },
      rules: {
        quantity: [
          { required: true, message: '总库存不能为空', trigger: 'blur' }
        ],
        applyQuantity: [
          { required: true, message: '可用库存不能为空', trigger: 'blur' }
        ],
        occupyQuantity: [
          { required: true, message: '占用库存不能为空', trigger: 'blur' }
        ],
        frozenQuantity: [
          { required: true, message: '冻结库存不能为空', trigger: 'blur' }
        ],
        firstEnterDate: [
          { required: true, message: '第一次入库时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  dicts: ['logOperationType', 'stockLogBusinessType'],
  cruds() {
    return CRUD({
      title: '仓储管理', url: 'stock/page', sort: 'id:desc', crudMethod: { ...crudStock },
      optShow: {
        add: false,
        edit: false,
        del: false,
        download: false,
        reset: false
      }
    })
  },
  mounted() {
    depotApi.getAll().then(res => {
      for (let i = 0; i < res.data.length; i++) {
        this.list.push({ label: res.data[i].name, value: res.data[i].id })
      }
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    open() {
      this.dialogVisible = true
    },
    choose() {
      this.$refs.chooseProduct.open()
    },
    stockLog(rows) {
      this.logData = []
      crudStock.stockLog(rows.productId, rows.depotId).then(res => {
        this.visible = true
        for (let i = 0; i < res.data.rows.length; i++) {
          this.logData.push(res.data.rows[i])
        }
      })
    },
    initializeWarehouse() {
      crudStock.init(this.tableData).then(() => {
        this.crud.refresh()
      })
      this.tableData = []
      this.dialogVisible = false
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.vendorOptions = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.vendorOptions = []
      }
    },
    childNotify(params) {
      console.log(params)
      if (params.length === 0) {
        this.$message.error('请选择商品')
      } else {
        for (var item of params) {
          if (this.arrId.indexOf(item.product.productId) === -1) {
            this.arrId.push(item.product.productId)
            this.nameCn.push(item.product.nameCn)
            this.pic.push(item.product.pic)
            this.tableData.push({ 'sku': item.product.sku, 'productId': item.product.productId })
          }
        }
        this.$refs.chooseProduct.close()
      }
      console.log('tableData')
      console.log(this.tableData)
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    filterTypeHandler(value, row) {
      return row.type.toString() === value
    },
    filterSBTHandler(value, row) {
      return row.stockLogBusinessType.toString() === value
    },
    sortChange(column) {
      const sortColumn = column.prop
      if (column.order === 'ascending') {
        this.crud.sort = [sortColumn + ':asc']
      }
      if (column.order === 'descending') {
        this.crud.sort = [sortColumn + ':desc']
      }
      this.crud.refresh()
    }
  }
}
</script>

<style>
.button3 {
  right: 2%;
  position: absolute;
  top: 95%;
}

.button4 {
  right: 9%;
  position: absolute;
  top: 95%;
}

.tableImg {
  width: 50px;
  margin-right: 6px;
  float: left;
}
</style>
